﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Text;

using BLL;
using Utility;

namespace EvaluationSystem.Answer
{
    public partial class QuestionRepeat : System.Web.UI.Page
    {
        private QuestionStatusBLL m_QuestionStatusBll = new QuestionStatusBLL();
        private TesterInfoBLL m_TesterInfoBll = new TesterInfoBLL();
        private DimensionBLL m_DimensionBll = new DimensionBLL();
        private ActivityBLL m_ActivityBll = new ActivityBLL();
        private QuestionBLL m_QuestionBll = new QuestionBLL();
        private GuidBLL m_GuidBll = new GuidBLL();
        private int m_QuestionNum = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["isTesting"] == null)//如果没有输入序列号，则禁止访问此页面
                {
                    Response.Redirect("Tlogin.aspx");
                }

                if (Request.QueryString["logopath"] != null)
                {
                    if (string.IsNullOrEmpty(Request.QueryString["logopath"]))
                    {
                        usrLogo.ImageUrl = "~/images/5050.jpg";
                        usrLogo.Visible = false;
                    }
                    else
                    {
                        usrLogo.ImageUrl = Request.QueryString["logopath"].ToString().Replace("\\","/");
                    }
                }
                if (Request["guid"] != null)
                {
                    if (CacheManager.Get("guid_" + Request["guid"].ToString()) == null)
                    {
                        CacheManager.Add("guid_" + Request["guid"].ToString(), 1, null);
                    }
                    if (CacheManager.Get("currentQNumber_" + Request["guid"].ToString()) == null)
                    {
                        CacheManager.Add("currentQNumber_" + Request["guid"].ToString(), 0, "guid");
                    }

                    //计算总时间
                    if (CacheManager.Get("QuestionTotalMinutes_" + Request["guid"].ToString()) == null)
                    {
                        CacheManager.Add("QuestionTotalMinutes_" + Request["guid"].ToString(),
                            m_QuestionBll.GetQuestionTimeByGUID(Request["guid"].ToString(),1), "");
                    }

                    if (CacheManager.Get("question_dt_" + Request["guid"].ToString()) == null)
                    {
                        QuestionBLL qbl = new QuestionBLL();
                        DataSet dsQuestion = qbl.GetQuestionByGUIDRand(Request["guid"].ToString(), out m_QuestionNum);
                        if (dsQuestion == null || dsQuestion.Tables[0].Rows.Count < 1)
                        {
                            MessageBox.ShowAndRedirect(this, "找不到相应的题目，请检查测评项目的维度设置!!", "Tlogin.aspx");
                            return;
                        }
                        DataTable dtQuestion = dsQuestion.Tables[0];
                        CacheManager.Add("question_dt_" + Request["guid"].ToString(), dtQuestion, "guid");

                        //增加2个特殊题目
                        DataRow dataRow = dtQuestion.NewRow();
                        dataRow[0] = -1;
                        dataRow[1] = 0;
                        dataRow[2] = "现实很难讲清楚什么是对的,什么是错的";
                        dataRow[3] = "是";
                        dataRow[4] = "不是";
                        dataRow[8] = 0;
                        dataRow[9] = 0;
                        dataRow[13] = 0;
                        dataRow[14] = 0;
                        dataRow[15] = 0;

                        DataRow dataRow2 = dtQuestion.NewRow();
                        
                        dataRow2[0] = -2;
                        dataRow2[1] = 0;
                        dataRow2[2] = "现实很难讲清楚什么是对的,什么是错的";
                        dataRow2[3] = "是";
                        dataRow2[4] = "不是";
                        dataRow2[8] = 0;
                        dataRow2[9] = 0;
                        dataRow2[13] = 0;
                        dataRow2[14] = 0;
                        dataRow2[15] = 0;

                        ((DataTable)CacheManager.Get("question_dt_" + Request["guid"].ToString())).Rows.InsertAt(dataRow, 0);
                        CacheManager.Add("questionNum_" + Request["guid"].ToString(), m_QuestionNum, "guid");
                        ((DataTable)CacheManager.Get("question_dt_" + Request["guid"].ToString())).Rows.InsertAt(dataRow2, m_QuestionNum + 1);

                        //智力类题目的标志位
                        if (CacheManager.Get("zhiliFlag_" + Request["guid"].ToString()) == null)
                        {
                            CacheManager.Add("zhiliFlag_" + Request["guid"].ToString(),
                                m_QuestionNum.ToString(), "");
                        }
                        //智力类题目的标志位
                    }

                    int nCur = (int)CacheManager.Get("currentQNumber_" + Request["guid"].ToString());
                    bind(nCur);

                    lblPosition.Text= m_TesterInfoBll.GetPositionByGUID(Request["guid"].ToString());
                    lblName.Text = m_TesterInfoBll.GetUserNameByGUID(Request["guid"].ToString());
                    
                    //记录答题者开始考试时间
                    m_TesterInfoBll.UpdateTesterInfo(Request["guid"].ToString(), "tester_teststarttime", DateTime.Now.ToString());

                    //记录开始答题时间
                    if (CacheManager.Get("QuestionUsedMinutes_" + Request["guid"].ToString()) == null)
                    {
                        DataSet ds = m_TesterInfoBll.GetListByGuid(Request["guid"].ToString());
                        if (ds != null)
                        {
                            DateTime dtStart = DateTime.Parse(ds.Tables[0].Rows[0]["tester_teststarttime"].ToString());
                            CacheManager.Add("QuestionUsedMinutes_" + Request["guid"].ToString(), dtStart, "");
                        }
                    }

                    //测试中
                    m_GuidBll.UpdateStatus(Request["guid"].ToString(), 1);
                }
            }

            updateQuestionProgress();
            updateTimeProgress();
        }

        private void updateQuestionProgress()
        {
            if (CacheManager.Get("question_dt_" + Request["guid"].ToString()) != null && 
                CacheManager.Get("currentQNumber_" + Request["guid"].ToString()) != null)
            {
                double totalQNum = (double)((DataTable)CacheManager.Get("question_dt_" + Request["guid"].ToString())).Rows.Count;
                double currentQNum = (double)((int)CacheManager.Get("currentQNumber_" + Request["guid"].ToString()));
                
                int n = Int32.Parse(((currentQNum) / totalQNum).ToString("0%").Replace("%",""));

                StringBuilder sb = new StringBuilder();
                sb.Append("$(document).ready(function() {");
                sb.Append("$('#questionprogressbar').progressbar({value:");
                sb.Append(n.ToString());
                sb.Append("});");
                sb.Append("});");
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "jQueryScript", sb.ToString(), true);
            }
        }

        private void updateTimeProgress()
        {
            DateTime dtStart = DateTime.Parse(CacheManager.Get("QuestionUsedMinutes_" + Request["guid"].ToString()).ToString());
            double usedSecs = (DateTime.Now - dtStart).TotalSeconds;

            double totalSec = 0;
            if (CacheManager.Get("QuestionTotalMinutes_" + Request["guid"].ToString()) != null)
            {
                totalSec = double.Parse(CacheManager.Get("QuestionTotalMinutes_" + Request["guid"].ToString()).ToString());
            }

            int n = Int32.Parse((usedSecs / totalSec).ToString("0%").Replace("%", ""));

            StringBuilder sb = new StringBuilder();
            sb.Append("$(document).ready(function() {");
            sb.Append("$('#timeprogressbar').progressbar({value:");
            sb.Append(n.ToString());
            sb.Append("});");
            sb.Append("});");
            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "jQueryScript2", sb.ToString(), true);
            //UpdatePanel1.Update();
        }

        private void bind(int rowNumber)
        {
            try
            {
                DataTable dt = (DataTable)CacheManager.Get("question_dt_" + Request["guid"].ToString());
                if (dt == null) return;

                spanTitle.InnerHtml = (rowNumber + 1).ToString() + ".　" +
                    dt.Rows[rowNumber]["question_title"].ToString();
                spanA.InnerHtml = dt.Rows[rowNumber]["question_answer_A"].ToString();
                spanB.InnerHtml = dt.Rows[rowNumber]["question_answer_B"].ToString();
                spanC.InnerHtml = dt.Rows[rowNumber]["question_answer_C"].ToString();
                spanD.InnerHtml = dt.Rows[rowNumber]["question_answer_D"].ToString();
                spanE.InnerHtml = dt.Rows[rowNumber]["question_answer_E"].ToString();

                spanA.Visible = rdoA.Visible =
                    (string.IsNullOrEmpty(dt.Rows[rowNumber]["question_answer_A"].ToString()) ? false : true);
                spanB.Visible = rdoB.Visible =
                   (string.IsNullOrEmpty(dt.Rows[rowNumber]["question_answer_B"].ToString()) ? false : true);
                spanC.Visible = rdoC.Visible =
                   (string.IsNullOrEmpty(dt.Rows[rowNumber]["question_answer_C"].ToString()) ? false : true);
                spanD.Visible = rdoD.Visible =
                   (string.IsNullOrEmpty(dt.Rows[rowNumber]["question_answer_D"].ToString()) ? false : true);
                spanE.Visible = rdoE.Visible =
                   (string.IsNullOrEmpty(dt.Rows[rowNumber]["question_answer_E"].ToString()) ? false : true);

                //智力类题目的标志位
                int zhiliFlag = 0;
                if (CacheManager.Get("zhiliFlag_" + Request["guid"].ToString()) != null)
                {
                    zhiliFlag = Int32.Parse(CacheManager.Get("zhiliFlag_" + Request["guid"].ToString()).ToString());
                }

                if (rowNumber >= (zhiliFlag + 2) && zhiliFlag > 0)
                {
                    lblTxt.Text = "请选择您认为正确的一项";
                }
                else
                {
                    lblTxt.Text = "请根据第一反应选择最符合或者最接近自己客观情况的那一项";
                }
                //智力类题目的标志位

                CacheManager.Add("StartDateTime_" + Request["guid"].ToString(), DateTime.Now, "guid");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void rdo_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                RadioButton rdoBtn = (RadioButton)sender;
                DataTable dt = (DataTable)CacheManager.Get("question_dt_" + Request["guid"].ToString());
                if (dt == null || rdoBtn == null) return;

                int currentQNumber = (int)CacheManager.Get("currentQNumber_" + Request["guid"].ToString());
                int qID = int.Parse(dt.Rows[currentQNumber]["question_id"].ToString());
                DataTable dtUsrSelected = (DataTable)CacheManager.Get("usrSelected_" + Request["guid"].ToString());
                
                if (dtUsrSelected == null)
                {
                    dtUsrSelected = new DataTable("usrSelected");

                    dtUsrSelected.Columns.Add("test_sn");
                    dtUsrSelected.Columns.Add("question_id");
                    dtUsrSelected.Columns.Add("question_selected");
                    dtUsrSelected.Columns.Add("question_is_dirty");
                    dtUsrSelected.Columns.Add("question_start_dt");
                    dtUsrSelected.Columns.Add("question_end_dt");
                }

                DataRow dr = dtUsrSelected.NewRow();

                dr["test_sn"]= Request["guid"].ToString();
                dr["question_id"]= qID;
                dr["question_selected"]= rdoBtn.Text;
                dr["question_is_dirty"]= 1;
                dr["question_start_dt"] = (DateTime)CacheManager.Get("StartDateTime_" + Request["guid"].ToString());
                dr["question_end_dt"]= DateTime.Now;

                dtUsrSelected.Rows.Add(dr);
                dtUsrSelected.AcceptChanges();

                CacheManager.Add("usrSelected_" + Request["guid"].ToString(), dtUsrSelected, "guid");//用户选择答题记录表

                int totalQNum = ((DataTable)CacheManager.Get("question_dt_" + Request["guid"].ToString())).Rows.Count;
                int currentQNum = ((int)CacheManager.Get("currentQNumber_" + Request["guid"].ToString()));

                if (currentQNum + 1 < totalQNum)//答题过程中
                {
                    CacheManager.Add("currentQNumber_" + Request["guid"].ToString(), (currentQNum + 1), "guid");
                    bind(currentQNum + 1);
                    rdoBtn.Checked = false;
                }
                else//已经是最后一题，进行答题结束处理.
                {
                    if (CacheManager.Get("isTestEnd_" + Request["guid"].ToString()) == null)
                    {
                        CacheManager.Add("isTestEnd_" + Request["guid"].ToString(), 1, "guid");
                        Response.Redirect("TestEnd.aspx?guid=" + Request["guid"].ToString());
                    }
                }
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }
}